#!/bin/bash
#
# This file is part of util-linux.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
TS_TOPDIR="${0%/*}/../.."
TS_DESC="fsck images"

. $TS_TOPDIR/functions.sh
ts_init "$*"

# inode contains UID and GID, use always UID=0 to get the same checksum
# TODO any mkfs should use UID=0 per default (custom uid optionally) like mk2fs
ts_skip_nonroot

ts_check_test_command "$TS_CMD_FSCKMINIX"
ts_check_test_command "$TS_HELPER_MKFS_MINIX"
ts_check_test_command "$TS_CMD_HEXDUMP"

# on big endian systems some of the subtests have different expected output
BYTE_ORDER=$($TS_HELPER_SYSINFO byte-order)
BE_EXT=$(test "$BYTE_ORDER" = "BE" && echo ".BE")

export MKFS_MINIX_TEST_SECOND_SINCE_EPOCH='1438460212'

check_minix_fs_type() {
	ts_init_subtest $1
	TS_EXPECTED+=$BE_EXT
	img=${TS_OUTPUT}.img
	dd if=/dev/zero bs=1024 count=16 of=$img >/dev/null 2>&1
	$TS_HELPER_MKFS_MINIX $2 $img >> $TS_OUTPUT 2>> $TS_ERRLOG
	echo "mkfs return value: $?" >> $TS_OUTPUT
	$TS_CMD_FSCKMINIX $img >> $TS_OUTPUT 2>> $TS_ERRLOG
	echo "fsck return value: $?" >> $TS_OUTPUT
	$TS_CMD_HEXDUMP -C $img >> $TS_OUTPUT 2>> $TS_ERRLOG
	rm -f $img
	ts_finalize_subtest
}

check_minix_fs_type 'v1c14' '-1 -n 14'
check_minix_fs_type 'v1c30' '-1 -n 30'
check_minix_fs_type 'v2c14' '-2 -n 14'
check_minix_fs_type 'v2c30' '-2 -n 30'
check_minix_fs_type 'v3c60' '-3 -n 60'

bad="$TS_OUTDIR/${TS_TESTNAME}.badlist"
# TODO seems that mkfs produces non-sense if badblocks are greater than device.
echo -e "8\n9" > $bad

# NOTE, -c with -l ignores -l.
check_minix_fs_type 'check-blocks' "-l $bad -c"
check_minix_fs_type 'badblocks' "-l $bad"

rm -f $bad

# no more big endian tests below
if test "$BYTE_ORDER" = "BE"; then
	ts_finalize
fi

# NOTE this seems odd: a 2nd fsck run would again modify the FS
ts_init_subtest "auto-fix"
img=${TS_OUTPUT}.img
cp "$TS_SELF/broken-root" $img
$TS_CMD_FSCKMINIX -sav $img >> $TS_OUTPUT 2>> $TS_ERRLOG
echo "fsck reports changed and uncorrected: $?" >> $TS_OUTPUT
$TS_CMD_HEXDUMP -C $img >> $TS_OUTPUT 2>> $TS_ERRLOG
sed -i 's/Filesystem on .* is dirty/Filesystem auto-fix is dirty/' $TS_OUTPUT $TS_ERRLOG
ts_finalize_subtest

ts_init_subtest "bug.773892"
"$TS_CMD_FSCKMINIX" -f "$TS_SELF/debian.bug.773892" 2>&1 >/dev/null
echo "fsck reports uncorrected: $?" >> $TS_OUTPUT
ts_finalize_subtest

ts_init_subtest "broken-root"
"$TS_CMD_FSCKMINIX" "$TS_SELF/broken-root" >> $TS_OUTPUT 2>> $TS_ERRLOG
echo "fsck reports uncorrected: $?" >> $TS_OUTPUT
ts_finalize_subtest

ts_finalize
